home *** CD-ROM | disk | FTP | other *** search
- Path: hubcap.clemson.edu!hubcap!mjs
- From: mjs@hubcap.clemson.edu (M. J. Saltzman)
- Newsgroups: comp.lang.c
- Subject: Re: free space malloced to auto vars??
- Date: 3 Feb 96 21:26:43 GMT
- Organization: Clemson University
- Message-ID: <mjs.823382803@hubcap>
- References: <4eqf8m$smv@gsusgi1.gsu.edu> <9602032047.AA28443@dxmint.cern.ch>
- NNTP-Posting-Host: hubcap.clemson.edu
-
- Dan Pop <danpop@mail.cern.ch> writes:
-
- |matmrlx@gsusgi1.gsu.edu (Michael R. Lauer) writes:
- |>The general question is: if you malloc space for a pointer with automatic
- |>storage, should/must you free that space before leaving that scope?
-
- |Yes. However, I can't see any malloc call in your example.
- |>
- |>This seems obvious but it is giving me trouble. In this code:
- |>
- |>{
- |> struct dirent *dp;
- |> if ((dp = readdir() != NULL)
- | ^^^^^^^^^
- |This is a bad function call and it's likely to generate a segmentation
- |fault.
-
- ObC:
- In addition, although it's hard to know for sure if this is a real
- problem (since the parentheses are unbalanced, so the fragment won't
- even compile), as it is written, this expression assigns dp the value
- 0 if readdir() returns NULL and 1 otherwise. If readdir() returns a
- valid pointer, then when you go to free(dp), you will pass free() an
- invalid pointer.
-
- |> {
- |> }
- |> if (dp) /* this seems to cause a segmentation fault */
- |> free(dp); /* when the enclosing function returns */
- |>}
-
- I'll leave this excellent advice here:
-
- |NEVER free a pointer initialized by a library function (with the possible
- |exception of the nonstandard strdup).
-
- |Then call closedir() before returning from the function. If the
- |documentation doesn't mention the need to call free(dp), then don't do it.
- |If you break the rules, you get what you deserve.
-
- |BTW, readdir is not a standard C function, so the question should have been
- |posted to comp.unix.programmer.
- --
- Matthew Saltzman
- Clemson University Math Sciences
- mjs@clemson.edu
-